<script setup lang="ts">
import { ref } from 'vue'
import AddressPanel from './components/AddressPanel.vue'
import ServicePanel from './components/ServicePanel.vue'
import type { SkuPopupLocaldata } from '@/components/vk-data-goods-sku-popup/vk-data-goods-sku-popup'
import { onLoad } from '@dcloudio/uni-app'
import { getGoodsByIdAPI } from '@/services/goods'
import { postShopCartAPI } from '@/services/Zcart'
import type { CategoryItems } from '@/types/goods'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 轮播图变化时
const currentIndex = ref(0)
const onChange: UniHelper.SwiperOnChange = (ev) => {
  currentIndex.value = ev.detail.current
}
// uni-ui 弹出层组件 ref
const popup = ref<{
  open: () => void
  close: () => void
}>()
// 弹出层条件渲染
const popupName = ref<'address' | 'service'>()
const openPopup = (name: typeof popupName.value) => {
  // 修改弹出层名称
  popupName.value = name
  // 打开弹出层
  popup.value?.open()
}
// 是否显示SKU组件
const isShowSku = ref(false)
// 商品数据（插件格式）
let transformedGoodsInfo: SkuPopupLocaldata = {
  _id: '',
  name: '',
  goods_thumb: '',
  sku_list: [],
  spec_list: [],
}
// 商品数据（插件格式），使用 ref 包装
const goodsInfo = ref<SkuPopupLocaldata>({
  _id: '',
  name: '',
  goods_thumb: '',
  sku_list: [],
  spec_list: [],
})

/* 接收页面参数 */
const query = defineProps<{
  id: string
}>()
/* 根据id获取商品详情数据 */
const GoodList = ref<CategoryItems>()
const getGoods = async () => {
  try {
    const res = await getGoodsByIdAPI(query.id)
    GoodList.value = res.data.info_list[0]
    console.log('商品详情数据:', GoodList.value)

    // 转换数据为插件格式
    goodsInfo.value = transformGoodsData(GoodList.value)
    console.log('转换后的数据23333：', goodsInfo.value)
  } catch (error) {
    console.error('获取商品详情失败:', error)
  }
}
// 数据转换函数
function transformGoodsData(goods: CategoryItems): SkuPopupLocaldata {
  if (!goods) return transformedGoodsInfo

  // 商品基本信息
  transformedGoodsInfo = {
    _id: goods.id.toString(),
    name: goods.name,
    goods_thumb: goods.pictureList.length > 0 ? goods.pictureList[0].url : '',
    sku_list: [],
    spec_list: [],
  }

  // 处理规格列表
  if (goods.spec && goods.spec.length > 0) {
    const specList = {
      name: '规格', // 规格名称
      list: goods.spec.map((item) => ({ name: item.specname })),
    }
    transformedGoodsInfo.spec_list.push(specList)
  }

  // 处理 SKU 列表
  if (goods.spec && goods.spec.length > 0) {
    goods.spec.forEach((spec, index) => {
      transformedGoodsInfo.sku_list.push({
        _id: `${goods.id}_spec_${index + 1}`, // SKU ID
        goods_id: goods.id.toString(),
        goods_name: goods.name,
        image: goods.pictureList.length > 0 ? goods.pictureList[0].url : '',
        price: spec.price * 100, // 插件默认会除以 100，所以这里乘以 100
        sku_name_arr: [spec.specname], // 单规格情况下只有一个值
        stock: spec.stock,
      })
    })
  }

  return transformedGoodsInfo
}

// 新增：加入购物车的函数
const addToCart = () => {
  // console.log('加入购物车按钮被点击了')
  // console.log('商品信息：', goodsInfo.value)
  isShowSku.value = true
  // 在这里可以添加购物车逻辑，例如调用 API 或更新状态
}

// 父组件处理子组件触发的 add-cart 事件
const handleAddCart = (selectShop) => {
  console.log('父组件捕获到 add-cart 事件')
  console.log('选中的商品信息：', selectShop)

  // 检查商品信息是否已加载
  if (!selectShop.goods_id) {
    uni.showToast({
      icon: 'none',
      title: '商品信息未加载，请稍后再试',
    })
    return
  }

  // 构造请求参数
  const cartData = {
    meal_id: parseInt(selectShop.goods_id), // 商品 ID
    meal_name: selectShop.goods_name, // 商品名称
    meal_spec: selectShop.sku_name_arr[0], // 规格名称
    count: selectShop.buy_num || 1, // 使用 buy_num 或默认为 1
  }

  // 调用购物车接口
  postShopCartAPI(cartData, '1', '10')
    .then((res) => {
      console.log('加入购物车成功', res)
      uni.showToast({
        icon: 'success',
        title: '已加入购物车',
      })
      // 关闭 SKU 弹窗
      isShowSku.value = false
    })
    .catch((err) => {
      console.error('加入购物车失败', err)
      uni.showToast({
        icon: 'none',
        title: '加入购物车失败，请稍后再试',
      })
    })
}
// 购物车end
onLoad(() => {
  console.log('商品详情页当前商品id:', query.id)
  getGoods()
})
</script>

<template>
  <scroll-view scroll-y class="viewport">
    <!-- 基本信息 -->
    <view class="goods">
      <!-- 商品主图 -->
      <view class="preview">
        <swiper @change="onChange" circular>
          <swiper-item v-for="item in GoodList?.pictureList" :key="item.url">
            <image mode="aspectFill" :src="item.url || ''" />
          </swiper-item>
        </swiper>
        <view class="indicator">
          <text class="current">{{ currentIndex + 1 }}</text>
          <text class="split">/</text>
          <text class="total">9</text>
        </view>
      </view>

      <!-- 商品简介 -->
      <view class="meta">
        <view class="price">
          <text class="symbol">¥</text>
          <text class="number">{{ GoodList?.spec[0]?.price }}</text>
        </view>
        <view class="name ellipsis">{{ GoodList?.name }} </view>
        <view class="desc"> {{ GoodList?.mealdesc }} </view>
      </view>

      <!-- 操作面板 -->
      <view class="action">
        <view class="item arrow" @tap="isShowSku = true">
          <text class="label">选择</text>
          <text class="text ellipsis"> 请选择商品规格 </text>
          <text class="iconfont icon-arrow-right-s-line"></text>
        </view>
        <!-- <view class="item arrow" @tap="openPopup('address')">
          <text class="label">送至</text>
          <text class="text ellipsis"> 请选择收获地址 </text>
          <text class="iconfont icon-arrow-right-s-line"></text>
        </view>
        <view class="item arrow" @tap="openPopup('service')">
          <text class="label">服务</text>
          <text class="text ellipsis"> 无忧退 快速退款 免费包邮 </text>
          <text class="iconfont icon-arrow-right-s-line"></text>
        </view> -->
      </view>
    </view>
    <!-- SKU弹窗组件 -->
    <vk-data-goods-sku-popup v-model="isShowSku" :localdata="goodsInfo" @add-cart="handleAddCart" />
    <!-- 弹窗测试 -->
    <!-- <button @tap="isShowSku = true">打开 SKU 弹窗</button> -->
  </scroll-view>

  <!-- 用户操作 -->
  <view class="toolbar" :style="{ paddingBottom: safeAreaInsets?.bottom + 'px' }">
    <view class="buttons">
      <view class="addcart" @click="addToCart"> 加入购物车 </view>
    </view>
  </view>
  <!-- uni-ui 弹出层 -->
  <uni-popup ref="popup" type="bottom" background-color="#fff">
    <AddressPanel v-if="popupName === 'address'" @close="popup?.close()" />
    <ServicePanel v-if="popupName === 'service'" @close="popup?.close()" />
  </uni-popup>
</template>

<style lang="scss">
page {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.viewport {
  background-color: #f4f4f4;
}

.panel {
  margin-top: 20rpx;
  background-color: #fff;

  .title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 90rpx;
    line-height: 1;
    padding: 30rpx 60rpx 30rpx 6rpx;
    position: relative;

    text {
      padding-left: 10rpx;
      font-size: 28rpx;
      color: #333;
      font-weight: 600;
      border-left: 4rpx solid #27ba9b;
    }

    navigator {
      font-size: 24rpx;
      color: #666;
    }
  }
}

// .arrow {
//   &::after {
//     position: absolute;
//     top: 50%;
//     right: 30rpx;
//     content: '\e747';
//     color: #ccc;
//     font-family: 'erabbit' !important;
//     font-size: 32rpx;
//     transform: translateY(-50%);
//   }
// }
.icon-arrow-right-s-line {
  position: absolute;
  top: 50%;
  left: 95%;
  color: #ccc;

  font-size: 32rpx;
  transform: translateY(-50%);
}

/* 商品信息 */
.goods {
  background-color: #fff;

  .preview {
    height: 750rpx;
    position: relative;

    .image {
      width: 750rpx;
      height: 750rpx;
    }

    .indicator {
      height: 40rpx;
      padding: 0 24rpx;
      line-height: 40rpx;
      border-radius: 30rpx;
      color: #fff;
      font-family: Arial, Helvetica, sans-serif;
      background-color: rgba(0, 0, 0, 0.3);
      position: absolute;
      bottom: 30rpx;
      right: 30rpx;

      .current {
        font-size: 26rpx;
      }

      .split {
        font-size: 24rpx;
        margin: 0 1rpx 0 2rpx;
      }

      .total {
        font-size: 24rpx;
      }
    }
  }

  .meta {
    position: relative;
    border-bottom: 1rpx solid #eaeaea;

    .price {
      height: 130rpx;
      padding: 25rpx 30rpx 0;
      color: #fff;
      font-size: 34rpx;
      box-sizing: border-box;
      background-color: #35c8a9;
    }

    .number {
      font-size: 56rpx;
    }

    .brand {
      width: 160rpx;
      height: 80rpx;
      overflow: hidden;
      position: absolute;
      top: 26rpx;
      right: 30rpx;
    }

    .name {
      max-height: 88rpx;
      line-height: 1.4;
      margin: 20rpx;
      font-size: 32rpx;
      color: #333;
    }

    .desc {
      line-height: 1;
      padding: 0 20rpx 30rpx;
      font-size: 24rpx;
      color: #cf4444;
    }
  }

  .action {
    padding-left: 20rpx;

    .item {
      height: 90rpx;
      padding-right: 60rpx;
      border-bottom: 1rpx solid #eaeaea;
      font-size: 26rpx;
      color: #333;
      position: relative;
      display: flex;
      align-items: center;

      &:last-child {
        border-bottom: 0 none;
      }
    }

    .label {
      width: 60rpx;
      color: #898b94;
      margin: 0 16rpx 0 10rpx;
    }

    .text {
      flex: 1;
      -webkit-line-clamp: 1;
    }
  }
}

/* 商品详情 */
.detail {
  padding-left: 20rpx;

  .content {
    margin-left: -20rpx;

    .image {
      width: 100%;
    }
  }

  .properties {
    padding: 0 20rpx;
    margin-bottom: 30rpx;

    .item {
      display: flex;
      line-height: 2;
      padding: 10rpx;
      font-size: 26rpx;
      color: #333;
      border-bottom: 1rpx dashed #ccc;
    }

    .label {
      width: 200rpx;
    }

    .value {
      flex: 1;
    }
  }
}

/* 同类推荐 */
.similar {
  .content {
    padding: 0 20rpx 200rpx;
    background-color: #f4f4f4;
    display: flex;
    flex-wrap: wrap;

    .goods {
      width: 340rpx;
      padding: 24rpx 20rpx 20rpx;
      margin: 20rpx 7rpx;
      border-radius: 10rpx;
      background-color: #fff;
    }

    .image {
      width: 300rpx;
      height: 260rpx;
    }

    .name {
      height: 80rpx;
      margin: 10rpx 0;
      font-size: 26rpx;
      color: #262626;
    }

    .price {
      line-height: 1;
      font-size: 20rpx;
      color: #cf4444;
    }

    .number {
      font-size: 26rpx;
      margin-left: 2rpx;
    }
  }

  navigator {
    &:nth-child(even) {
      margin-right: 0;
    }
  }
}

/* 底部工具栏 */
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
  background-color: #fff;
  height: 100rpx;
  padding: 0 20rpx var(--window-bottom);
  border-top: 1rpx solid #eaeaea;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: content-box;
  justify-content: flex-end;
  .buttons {
    display: flex;

    & > view {
      width: 220rpx;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
    }

    .addcart {
      background-color: #ffa868;
      // width: 100%;
      text-align: center;
      line-height: 72rpx;
      font-size: 26rpx;
      color: #fff;
      border-radius: 72rpx;
    }

    .buynow,
    .payment {
      background-color: #27ba9b;
      margin-left: 20rpx;
    }
  }

  .icons {
    padding-right: 10rpx;
    display: flex;
    align-items: center;
    flex: 1;

    .icons-button {
      flex: 1;
      text-align: center;
      line-height: 1.4;
      padding: 0;
      margin: 0;
      border-radius: 0;
      font-size: 20rpx;
      color: #333;
      background-color: #fff;

      &::after {
        border: none;
      }
    }

    text {
      display: block;
      font-size: 34rpx;
    }
  }
}
</style>
